var express = require('express')
var User = require('../../models/User')
var md5 = require('blueimp-md5')
var gravatar = require('gravatar');
var jwt = require('jsonwebtoken')
var passport=require('passport')
var router = express.Router()
router.get('/get', function (req, res) {
    res.json({
        status: 0,
        msg: 'login works12316'
    })
})
// 注册api
router.post('/register', function (req, res) {
    //    查询数据库是否拥有此邮箱或者user
    var body = req.body
    User.findOne({
        $or: [{ name: body.name }, { email: body.email }]
    }, function (error, user) {
        if (user) {
            return res.status(200).json({
                err_code: 1,
                msg: 'name or email invalid'
            })
        }
        // 修改密码用md5加密
        body.password = md5(md5(body.password))
        // 增加avatar头像属性
        body.avatar = gravatar.url(body.email, { s: '200', r: 'pg', d: 'mm' });
        new User(body).save(function (err, user) {
            if (err) {
                return res.json({
                    err_code: 500,
                    msg: res.message
                })
            }
            res.json({
                err_code: 0,
                msg: 'regiser ok!',
                
            })
        })
    }

    )

})

// 登陆api
router.post('/login', function (req, res) {
    var body = req.body
    User.findOne({
        email: body.email, password: md5(md5(body.password))
    }, function (err, user) {
        if (!user) {
            return res.status(200).json({
                err_code: 1,
                msg: "email or password invalid"
            })
        }
        // jwt.sign(自定义规则，secret,时常，回调函数)
        jwt.sign({ id: user.id }, 'secret', { expiresIn: 3600*24 }, function (err, token) {
            if (err) return
            res.json({
                err_code: 0,
                msg:"ok",
                token: "Bearer "+token
            })
        })

    })
})
// 验证token
router.get('/current', passport.authenticate('jwt',{session:false}),function (req, res) {
    res.json({
        id:req.user.id,
        name:req.user.name,
        email:req.user.email,
        identity:req.user.identity

    })
})
module.exports = router